import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
    Button, Menu, Dropdown, Icon, Row, Col,
    Input, Modal, Select, InputNumber, DatePicker, Table,
    Steps, Card, Checkbox, Popover, Badge, Tooltip, Divider, message, Popconfirm,
    Form,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import { routerRedux, Link } from 'dva/router';
import querystring from 'querystring';
import { createDecipher } from 'crypto';

const FormItem = Form.Item;
const { Description } = DescriptionList;
const { TextArea } = Input;
const { Step } = Steps;
const Option = Select.Option;
const monthFormat = 'YYYY-MM-DD';
/*
  产品详情修改
*/const EditableCell = ({ editable, value, onChange }) => (
    <div>
        {editable
            ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} />
            : value
        }
    </div>
);

@connect(({ product, channel }) => ({
    product, channel
}))

@Form.create()
export default class ProductDetails extends PureComponent {
    state = {
        productVariety: '',
        retailData: [],
        selectTimeType: false,
        endOpen: false,
        isEndTime: false,
        initRetailCount: 0,
        type: '',// 1是产品详情  2是产品审核  3是产品开通
        modalVisible: false,
        productId: '',
        productType: '',
        startTime: '',
        endTime: '',
        validTime: null,
        endTimeString: '',
        id: ''
    };

    componentDidMount() {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        this.setState({
            id: params.id,
        })
        dispatch({
            type: 'product/queryProductDetails',
            payload: {
                id: params.id,
            },
            callback: () => {
                const { product: { productDetails, channelList, retailsList } } = this.props;
                // console.log("productDetails",productDetails)
                productDetails &&
                    this.setState({
                        productDetailsList: productDetails,
                        productType: productDetails.productType,
                        validTime: productDetails.timeValid,
                        isEndTime: productDetails.timeValid == 0 ? false : true,
                        startTime: productDetails.beginTime == null ? null : moment(productDetails.beginTime),
                        endTime: (productDetails.timeValid == 1 || productDetails.endTime == null) ? null : moment(productDetails.endTime),
                        endTimeString: productDetails.timeValid == 1 ? null : moment(productDetails.endTime),
                    })
                if (productDetails.productType == 1) {
                    this.setState({
                        retailData: productDetails.productDiviList,
                    })
                }
                // console.log("startTime",this.state.startTime)
                // console.log("endTime",this.state.endTime)
            },
        });
    }

    handleProductSubmit = () => {
        const { dispatch } = this.props;
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                // console.log("handleProductSubmit", values)
                dispatch({
                    type: 'product/dredgeProduct',
                    payload: {

                    }
                });
            }
        });
    };

    handleProductCallback = () => {
        const { dispatch } = this.props;
        if (this.state.type == 3) {
            dispatch(routerRedux.push('/product/product-list'));
        } else {
            dispatch(routerRedux.push('/product/product-catalog'));
        }
    }

    handleRejected = () => {
        this.setState({
            modalVisible: true,
        })
    }

    handleAdustPrice = (item, e) => {
        const { dispatch } = this.props;
        item.adjustPrice = e.target.value;
        dispatch({
            type: 'channel/changeAddProduct',
            payload: {
                item
            },
        })
    }

    handleThroughSubmit = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'product/verifyProduct',
            payload: {
                id: this.state.productId,
                result: 1,
            },
            callback: () => {
                const { product: { productResult } } = this.props;
                if (productResult.code == '200') {
                    dispatch(routerRedux.push('/product/product-catalog'));
                    message.success("提交成功");
                } else {
                    message.error(productResult.message);
                }
            }
        });
    }

    handleOpinionOK = () => {
        const { dispatch } = this.props;
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                dispatch({
                    type: 'product/verifyProduct',
                    payload: {
                        id: this.state.productId,
                        result: 0,
                        ...values
                    },
                    callback: () => {
                        const { product: { productResult } } = this.props;
                        if (productResult.code == '200') {
                            this.setState({
                                modalVisible: false,
                            });
                            dispatch(routerRedux.push('/product/product-catalog'));
                            message.success("提交成功");

                        } else {
                            message.error(productResult.message);
                        }
                    }

                });
            }
        });
    }

    onChangeSelect = (value) => {
        this.setState({
            productType: value,
        });
    }

    onRetailData = () => {
        if (this.state.initRetailCount == 0) {
            for (let i = 1; i < 4; i++) {
                this.state.retailData.push({
                    key: i,
                    nper: `${(4 * i) * 3}`,
                    price: ` 0`,
                    type: 0,
                    isPreset: i <= 3,
                });
            }
            this.state.initRetailCount = 1
        }
    }

    //编辑
    editRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
            target.editable = true;
            this.setState({ retailData: newData });
        }
    }
    //取消
    cancelRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.id)[0];
        // console.log("targetcancelRetail")
        // console.log(target)
        if (target) {
            Object.assign(target, this.cacheDataRetail.filter(item => key === item.id)[0]);
            delete target.editable;
            this.setState({ retailData: newData });
        }
    }
    //保存
    saveRetail(key) {
        const newData = [...this.state.retailData];
        const target = newData.filter(item => key === item.id)[0];
        // console.log("targetsaveRetail")
        // console.log(target)
        if (target) {
            if (target.nper !== "" && target.price !== "") {
                delete target.editable;
                this.setState({ retailData: newData });
                this.cacheDataRetail = newData.map(item => ({ ...item }));
            } else {
                message.error("请先填写期数和价格")
            }
        }
    }
    //删除
    deleteRetail(key) {
        const newData = [...this.state.retailData];
        this.setState({ retailData: newData.filter(item => item.id !== key) });
    }

    constructor(props) {
        super(props);
        this.renderDelete = (record) => {
            return (
                <span>
                    <a onClick={() => this.editRetail(record.id)}>编辑</a>
                    {!(record.nper == 12 || record.nper == 24 || record.nper == 36) &&
                        <Popconfirm title="确定要删除吗?" onConfirm={() => this.deleteRetail(record.id)}>
                            <Divider type="vertical" />
                            <a>删除</a>
                        </Popconfirm>}
                </span>
            );
        }
        this.columnsRetail = [{
            title: '期数',
            dataIndex: 'nper',
            key: 'nper',
            align: 'center',
            render: (text, record) => this.renderColumnsRetail(text, record, 'nper'),
        }, {
            title: '费率',
            dataIndex: 'price',
            key: 'price',
            align: 'center',
            render: (text, record) => this.renderColumnsRetail(text, record, 'price'),
        }, {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: '35%',
            render: (text, record) => {
                const { editable } = record;
                return (
                    <div className="editable-row-operations">
                        {editable ?
                            <span>
                                <a onClick={() => this.saveRetail(record.id)}>保存</a>
                                <Popconfirm title="确定要取消吗?" onConfirm={() => this.cancelRetail(record.id)}>
                                    <Divider type="vertical" />
                                    <a>取消</a>
                                </Popconfirm>
                            </span>
                            :
                            this.renderDelete(record)
                        }
                    </div>
                );
            },
        }];
        this.cacheDataRetail = this.state.retailData.map(item => ({ ...item }));
    }

    renderColumnsRetail(text, record, column) {
        return (
            (record.nper == 12 || record.nper == 24 || record.nper == 36) && column == 'nper' ?
                text
                :
                <EditableCell
                    editable={record.editable}
                    value={text}
                    onChange={value => this.handleChangeRetail(value, record.id, column)}
                />
        );
    }

    handleChangeRetail(value, key, column) {
        if (value != 12 && value != 24 && value != 36) {
            const newData = [...this.state.retailData];
            const target = newData.filter(item => key === item.id)[0];
            if (target) {
                target[column] = value;
                this.setState({ retailData: newData });
            }
        } else {
            message.warning(`${value}期已存在`)
        }
    }

    handleChangeChannel(value, key, column) {
        if (value != 12 && value != 24 && value != 36) {
            const newData = [...this.state.channelData];
            const target = newData.filter(item => key === item.id)[0];
            if (target) {
                target[column] = value;
                this.setState({ channelData: newData });
            }
        } else {
            message.warning(`${value}期已存在`)
        }
    }

    handleModalCancel = () => {
        this.setState({
            modalVisible: false,
        })
    }

    handleStartOpenChange = (open) => {
        if (!open) {
            this.setState({ endOpen: true });
        }
    }

    handleEndOpenChange = (open) => {
        this.setState({ endOpen: open });
    }

    handleChangeForeverTime = (e) => {

        if (this.state.endTime) {
            this.setState({
                validTime: e.target.checked,
                isEndTime: !this.state.isEndTime,
                endTime: this.state.endTimeString
            });
        } else {
            this.setState({
                validTime: e.target.checked,
                isEndTime: !this.state.isEndTime,
                endTime: ''
            });
        }
        // this.state.validTime == 1 ? this.setState({ isForever: false }) : this.setState({ isForever: true })
    }

    disabledStartDate = (startTime) => {
        const endTime = this.state.endTime;
        if (!startTime || !endTime) {
            return false;
        }
        return startTime.valueOf() > endTime.valueOf();
    }

    disabledEndDate = (endTime) => {
        const startTime = this.state.startTime;
        if (!endTime || !startTime) {
            return false;
        }
        return endTime.valueOf() <= startTime.valueOf();
    }

    onStartChange = (value) => {
        this.setState({
            startTime: value,
        });
    }

    onEndChange = (value) => {
        this.setState({
            endTime: value,
            selectTimeType: !this.state.selectTimeType
        })
    }

    //新增分期费率
    newMemberRetailData = () => {
        const newRetailList = [...this.state.retailData];
        const newRecord = {
            key: newRetailList.length + 1,
            id: newRetailList.length + 1,
            nper: '',
            price: '',
            type: 0,
            editable: true,
            isNew: true,
            isPreset: false,
        };
        newRetailList.push(newRecord);
        this.setState({
            retailData: newRetailList
        });
    }

    handleProductEditSubmit = () => {
        const { dispatch } = this.props;
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                // console.log("handleProductAdd values", values)
                // console.log("handleProductAddSubmit values", this.state.retailData)
                dispatch({
                    type: 'product/updateProductDetails',
                    payload: {
                        ...values,
                        id: this.state.id,
                        beginTime: this.state.startTime,
                        endTime: this.state.endTime,
                        timeValid: this.state.validTime ? 1 : 0,
                        // ProductDiviList: this.state.retailData
                    },
                    callback: () => {
                        const { product: { productResult } } = this.props
                        if (productResult.code == 200) {
                            dispatch(routerRedux.push('/product/product-catalog'));
                        } else {
                            message.error(productResult.message)
                        }
                    },
                });
            }
        });
    }

    render() {
        const { selectedRows, modalVisible } = this.state;
        const { product: { productDetails, productLoading } } = this.props;
        const { getFieldDecorator, validateFieldsAndScroll } = this.props.form;
        this.onRetailData();
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        const formItemLayout1 = {
            labelCol: {
                span: 11,
            },
            wrapperCol: {
                span: 13,
            },
        };

        return (
            <PageHeaderLayout
                title="产品详情"
            >
                {
                    // JSON.stringify('1111', this.state.productType)
                }
                <Card bordered={false}>
                    <Form>
                        <FormItem {...formItemLayout} label="产品编号" >
                            {
                                getFieldDecorator('productNum', {
                                    initialValue: productDetails && productDetails.productNum,
                                    rules: [{
                                        required: true, message: '请输入产品编号',
                                    }],
                                })(
                                    <Input placeholder="请输入产品编号" />
                                )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品名称" >
                            {
                                getFieldDecorator('productName', {
                                    initialValue: productDetails && productDetails.productName,
                                    rules: [{
                                        required: true, message: '请输入产品名称',
                                    }],
                                })(
                                    <Input placeholder="请输入产品名称" />

                                )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="资产种类" >
                            {getFieldDecorator('assetType', {
                                initialValue: productDetails && productDetails.assetType,
                            })(
                                <Select placeholder="请选择资产种类" onChange={this.handleAssetsTypeVariety}>
                                    <Option value={1}>新车</Option>
                                    <Option value={2}>二手车</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品种类" >
                            {getFieldDecorator('productType', {
                                initialValue: productDetails && productDetails.productType,
                            })(
                                <Select placeholder="请选择产品种类" onChange={this.onChangeSelect}>
                                    <Option value={1}>分期</Option>
                                    <Option value={0}>贷款</Option>
                                </Select>
                            )}
                        </FormItem>
                        {
                            this.state.productType == 0 ?
                                <FormItem {...formItemLayout} label="产品价格" >
                                    {getFieldDecorator('productPrice', {
                                        initialValue: productDetails && productDetails.productPrice,
                                    })(
                                        <InputNumber
                                            placeholder="请输入"
                                            style={{ width: '100%' }}
                                            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                        />
                                    )}
                                </FormItem>
                                :
                                null
                        }
                        {
                            this.state.productType == 1 ?
                                <FormItem {...formItemLayout} label="分期费率" >
                                    {getFieldDecorator('productPrice', {
                                        initialValue: productDetails && productDetails.productPrice,
                                    })(
                                        <div>

                                            <Table
                                                rowKey="key"
                                                style={{ marginTop: '15px' }}
                                                dataSource={this.state.retailData}
                                                columns={this.columnsRetail}
                                                pagination={false}
                                                size="small"
                                                bordered />
                                            <Button
                                                onClick={this.newMemberRetailData}
                                                style={{ width: '100%' }}
                                                type="primary" icon="plus">
                                                新增
                                    </Button>
                                        </div>
                                    )}
                                </FormItem>
                                : null
                        }
                        <FormItem {...formItemLayout} label="合作银行" >
                            {getFieldDecorator('bankName', {
                                initialValue: productDetails && productDetails.bankName,
                            })(
                                <Select placeholder="请选择合作银行">
                                    <Option value={'工商银行'}>工商银行</Option>
                                    <Option value={'农业银行'}>农业银行</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品额度" >
                            {getFieldDecorator('productSize', {
                                initialValue: productDetails && productDetails.productSize,
                            })(
                                <InputNumber
                                    placeholder="请输入产品额度"
                                    style={{ width: '100%' }}
                                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="产品描述" >
                            {getFieldDecorator('productDesc', {
                                initialValue: productDetails && productDetails.productDesc,
                            })(
                                <TextArea placeholder="请输入产品描述" rows={4} />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="生效时间" >
                            {getFieldDecorator('retail')(
                                // initialValue: moment(productDetails && productDetails.disabledStartDate),
                                <span>
                                    <div>
                                        <DatePicker
                                            disabledDate={this.disabledStartDate}
                                            showTime
                                            format={monthFormat}
                                            placeholder="开始时间"
                                            style={{ width: '45%' }}
                                            value={this.state.startTime}
                                            onChange={this.onStartChange}
                                            onOpenChange={this.handleStartOpenChange}
                                        />
                                        <DatePicker
                                            disabledDate={this.disabledEndDate}
                                            showTime
                                            style={{ marginLeft: 5 }}
                                            disabled={this.state.isEndTime}
                                            format={monthFormat}
                                            placeholder="结束时间"
                                            value={this.state.isEndTime ? null : this.state.endTime}
                                            style={{ width: '45%', marginLeft: '10px' }}
                                            onChange={this.onEndChange}
                                            open={this.state.endOpen}
                                            onOpenChange={this.handleEndOpenChange}
                                        />
                                    </div>
                                    <Checkbox
                                        checked={this.state.validTime == 1 ? true : false}
                                        style={{ marginTop: 10 }}
                                        disabled={this.state.selectTimeType}
                                        onChange={this.handleChangeForeverTime}
                                    >
                                        永久
                                    </Checkbox>
                                </span>
                            )}
                        </FormItem>
                        <FormItem
                            wrapperCol={{
                                xs: { span: 24, offset: 0 },
                                sm: {
                                    span: formItemLayout1.wrapperCol.span,
                                    offset: formItemLayout1.labelCol.span,
                                },
                            }}
                            label=""
                        >
                            <Button type="primary" onClick={this.handleProductEditSubmit} loading={productLoading}>
                                提交
                                </Button>
                            <Button style={{ marginLeft: 8 }}><Link to='/product/product-catalog'>返回</Link></Button>
                        </FormItem>
                    </Form>
                </Card>
            </PageHeaderLayout>
        );
    }
}
